<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount, provide } from "vue";
import BetterScroll, { BScrollInstance } from "better-scroll";
import { isEmpty } from "lodash";
import { getVehiclesTree } from "@/apis/vehicles";
import LetterL from "./LatterL.vue";
import BrandL from "./BrandL.vue";

export interface VehicleTreeChildren {
  id: string;
  indexNum: number;
  keyWord: string;
  name: string;
  nameEn: string;
  ndType: number;
  num: 0;
  carLogoUrl: string;
  childs: VehicleTreeChildren[];
}

export interface Options {
  name: string | null;
  nameEn: string | null;
  childs: VehicleTreeChildren[];
}
const options = ref<Options[]>([]);
interface Emits {
  (event: "on-load"): void;
  (event: "on-select", target: VehicleTreeChildren, ancestors: any[]): void;
}

const emits = defineEmits<Emits>();

const expandKey = ref(new Set<string>());
// provide("expandKey", expandKey);

let bs: BScrollInstance | null = null;
const bsContentRef = ref<HTMLUListElement | null>(null);

const selectedKey = ref<VehicleTreeChildren["id"] | null>(null);
const selectedTarget = ref<VehicleTreeChildren | null>(null);
const zimu = ref("");
const autoExpandIds = ref("");
function handleLetterClick(value: Options) {
  // console.log("触发了锚点");
  if (bsContentRef.value === null) return;
  // const targetEl = document.querySelector(`[data-letter="${letter}"]`);
  const targetEl = Array.from(bsContentRef.value.children).find((el) =>
    el.querySelector(`[data-letter="${value.name}"]`)
  ) as HTMLElement | null;
  if (targetEl) {
    bs?.scrollToElement(targetEl, 300, false, false);
  }
}

function initBetterScroll() {
  if (bs) {
    bs.destroy();
  }
  bs = new BetterScroll(".better-scroll", {
    mouseWheel: true,
    scrollbar: { fade: true },
    scrollX: true,
    scrollY: true,
    observeDOM: true,
  });
  bs.on("scroll", (pos: any) => {
    console.log(pos);
  });
}

watch(options, (newVal: any) => {
  if (!isEmpty(newVal)) {
    nextTick(() => {
      initBetterScroll();
    });
  }
});

onMounted(() => {
  loadVehiclesTree();
  initBetterScroll();
});

onBeforeUnmount(() => {
  if (bs) {
    bs.destroy();
  }
});

watch(
  () => selectedKey.value,
  (val: any) => {
    if (val === null) return;
    const result = findAncestors(val);
    emits("on-select", selectedTarget.value!, result);
  }
);

function findAncestors(targetId: string): VehicleTreeChildren[] {
  const ancestors: VehicleTreeChildren[] = [];

  function findAncestorsRec(node: VehicleTreeChildren): boolean {
    if (node.id === targetId) {
      ancestors.push(node);
      return true;
    }
    for (const child of node.childs) {
      if (findAncestorsRec(child)) {
        ancestors.push(node);
        return true;
      }
    }
    return false;
  }

  options.value.forEach((root: any) => {
    if (findAncestorsRec(root)) {
      return ancestors;
    }
  });

  return ancestors.reverse();
}
function handleBrandClick(target: VehicleTreeChildren) {
  selectedTarget.value = target;
}

// 处理品牌展开的事件
function handleBrandExpanded(brandId: string) {
  if (expandKey.value.has(brandId)) {
    expandKey.value.delete(brandId);
  } else {
    expandKey.value.add(brandId);
  }
  // 确保更新BetterScroll的位置
  if (bs) {
    bs.refresh();
  }
}
function handleSelected(target: VehicleTreeChildren) {
  selectedKey.value = target.id;
  selectedTarget.value = target;
}

const props = defineProps<{
  productType: String;
  searchKeyword: number;
}>();

watch(
  () => props.searchKeyword,
  (newVal: any) => {
    if (newVal !== undefined && newVal !== null && newVal != 0) {
      scrollToNodeByIdAndExpand(String(newVal));
    }
  },
  { immediate: true }
);
async function scrollToNodeByIdAndExpand(id: string) {
  // console.log("开始滚动,车型id：", id);
  let foundNode: VehicleTreeChildren | null = null;

  await nextTick();

  // 查找车型节点
  // getChildrenArray 函数应该返回所有车品牌节点的扁平数组
  const brandNodes = getChildrenArray(options.value);
  // console.log("处理后的", brandNodes);
  foundNode = findNode(id, brandNodes) || null;
  // console.log("寻找到的车型节点：", foundNode);

  if (foundNode) {
    // 从车型节点开始查找所有祖先节点
    const ancestors = findallParent(foundNode, brandNodes);
    // console.log("查找当前节点的所有祖先节点", ancestors);

    // 展开所有祖先节点以及当前节点
    const ancestorsIds = ancestors.map((a) => a.id).concat(foundNode.id);
    ancestorsIds.forEach((id) => expandKey.value.add(id));
    // 滚动到节点
    const targetElement = bsContentRef.value?.querySelector(
      `[data-id="${id}"]`
    ) as HTMLElement | null;
    if (targetElement) {
      bs?.scrollToElement(targetElement, 500, false, false);
    }
    //字母树的滚动
    const letter = zimu.value;
    // console.log("所属字母", letter);
    // 查找字母树组件中的对应节点
    const letterOption = options.value.find((option: any) => option.name === letter);
    // console.log("所属字母对应节点", letterOption);
    // 如果找到字母节点，触发选中事件并滚动到对应位置
    if (letterOption) {
      // 设置当前选中字母
      handleLetterClick(letterOption);
      // 滚动到字母位置（如果实现滚动逻辑）
      scrollToLetter(letter);
    }
  }
}

// scrollToLetter 函数用于滚动到特定的字母位置
function scrollToLetter(letter: string) {
  const letterElement = bsContentRef.value?.querySelector(
    `[data-letter="${letter}"]`
  ) as HTMLElement | null;
  if (letterElement) {
    bs?.scrollToElement(letterElement, 500, false, false);
  }
}
// 辅助函数，用于获取所有车品牌节点的数组
function getChildrenArray(options: Options[]): VehicleTreeChildren[] {
  // 这里我们使用 flatMap 来获取所有车品牌节点
  return options.flatMap((option) => option.childs);
}
// 查找所有父节点
function findallParent(
  node: VehicleTreeChildren,
  rootNodes: VehicleTreeChildren[]
): VehicleTreeChildren[] {
  const ancestors: VehicleTreeChildren[] = [];

  function findAncestor(currentNode: VehicleTreeChildren): void {
    // 品牌
    for (const rootNode of rootNodes) {
      // 如果当前根节点的子节点中存在当前节点ID，将当前根节点作为父节点
      if (rootNode.childs.some((child) => child.id === currentNode.id)) {
        ancestors.unshift(rootNode); // 将找到的父节点添加到祖先数组
        // console.log("找品牌节点:", rootNode);
        zimu.value = rootNode.keyWord;
        selectedKey.value = node.id;

        // 继续查找父节点的父节点
        findAncestor(rootNode); // 递归查找父节点
        break; // 找到父节点后不需要继续循环
      }
      // 如果当前根节点的子节点还有子节点，递归检查这些子节点
      for (const child of rootNode.childs) {
        if (
          child.childs &&
          child.childs.some((grandchild) => grandchild.id === currentNode.id)
        ) {
          ancestors.unshift(child); // 将找到的父节点（车系或车品牌）添加到祖先数组
          // console.log("找到父节点（通过子节点）:", child);
          autoExpandIds.value = child.id; //车系节点
          zimu.value = rootNode.keyWord;
          selectedKey.value = node.id;

          // 递归查找父节点的父节点
          findAncestor(child); // 这里传入的是 child，即车系节点
          break;
        }
      }
    }
  }

  findAncestor(node);
  return ancestors;
}
// 查找节点
function findNode(id: string, nodes: VehicleTreeChildren[]): VehicleTreeChildren | null {
  for (const node of nodes) {
    if (node.id === id) {
      return node; // 找到匹配的节点
    }
    if (node.childs && node.childs.length > 0) {
      const foundNode = findNode(id, node.childs); // 递归搜索子节点
      if (foundNode) {
        return foundNode; // 如果在子节点中找到，返回找到的节点
      }
    }
  }
  return null; // 如果没有找到节点，返回null
}

const loadVehiclesTree = async () => {
  try {
    const productType = props.productType === "left" ? "0" : "1";
    const { data } = await getVehiclesTree({
      data: {
        productType: productType,
      },
    });
    options.value = data;
    // console.log("Vehicles Tree Data:", options.value);
  } catch (err) {
    console.error(err);
  }
};
function handleBrandExpandedFromChild(brandId: any) {
  handleBrandExpanded(brandId); // 调用子组件中相同的逻辑
}
</script>

<template>
  <div class="flex h-full">
    <!-- 字母树 -->
    <LetterL
      :options="options"
      :zimu="zimu"
      @on-select="handleLetterClick"
      style="
        position: relative;
        bottom: 0.4rem;
        left: -0.6rem;
        height: 100vh;
        width: 3rem;
      "
    />
    <!-- 字母树end -->
    <div class="relative flex-1 w-full h-full better-scroll">
      <ul ref="bsContentRef" class="flex flex-col p-0 m-0 list-none gap-y-6 pad">
        <template v-for="option in options" :key="option.key">
          <li class="inline-flex flex-col gap-4">
            <b class="w-8 text-center rounded bg-slate-200" :data-letter="option.name">
              {{ option.name }}
            </b>
            <template v-for="brand in option.childs" :key="brand.key">
              <BrandL
                :is-expanded="expandKey.has(brand.id)"
                :data-id="brand.id"
                :options="brand"
                :autoExpandIds="autoExpandIds"
                :isBrand="true"
                :select-key="selectedKey"
                @on-select="handleSelected"
                @click="() => handleBrandClick(brand)"
                @on-brand-expanded="handleBrandExpandedFromChild(brand.id)"
              />
            </template>
          </li>
        </template>
      </ul>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.better-scroll {
  overflow-x: auto;
  overflow-y: hidden;
}
/* 定义滚动条轨道的样式 */
.better-scroll::-webkit-scrollbar-track {
  background-color: #f5f5f5; /* 轨道背景色 */
  border-radius: 10px; /* 轨道圆角 */
}

/* 定义滚动条滑块的样式 */
.better-scroll::-webkit-scrollbar-thumb {
  background-color: #888888; /* 滑块背景色 */
  border-radius: 10px; /* 滑块圆角 */
}

/* 定义滚动条的宽度 */
.better-scroll::-webkit-scrollbar {
  width: 5px; /* 滚动条宽度 */
  height: 7px; /* 滚动条高度，对于横向滚动条，通常设置宽度即可 */
}
</style>
